<template>
  <div>
    <div class="task-containter">
      <!-- 第一步 -->
      <el-form ref="taskForm" :model="taskData" :rules="rules">
      <!-- 任务基本信息 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>任务基本信息</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 任务名称 -->
            <div class="common-item item-5">
              <label class="condition-label">任务名称</label>
              <el-form-item class="condition-input" prop="name">
                <el-input type="text" :disabled="taskData.done" placeholder="请输入任务名称" v-model="taskData.name" />
              </el-form-item>
            </div>
            <!-- 配置项 - 平台 -->
            <div class="common-item item-5">
              <label class="condition-label">社交平台</label>
              <el-form-item class="condition-input" prop="system">
                <el-select :disabled="taskData.done" v-model="taskData.system" clearable placeholder="请选择社交平台">
                  <el-option v-for="(item, index) in systems" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 配置项 - 类型 -->
            <!-- <div class="common-item item-3">
              <label class="condition-label">任务类型</label>
              <el-form-item class="condition-input" prop="system">
                <el-select :disabled="taskData.done" v-model="taskData.type" clearable placeholder="请选择类型">
                  <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div> -->
          </div>
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10">
              <label class="condition-label">任务描述</label>
              <el-form-item class="condition-input" prop="description">
                <el-input :disabled="taskData.done" v-model="taskData.description" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入任务描述" />
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 第一步配置 -->
      <div class="data-show">
        <!-- 标题 -->
        <div class="data-actions data-title-between">
          <h3>请求服务器公钥</h3> 
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-5">
              <label class="condition-label">用户名</label>
              <el-form-item class="condition-input" prop="userID">
                <el-input :disabled="taskData.done" type="text" v-model="taskData.userID" placeholder="请输入用户" />
              </el-form-item>
            </div>
            <!-- 配置项 - 算法类型 -->
            <div class="common-item item-5">
              <label class="condition-label">算法模块</label>
              <el-form-item class="condition-input" prop="keyType">
                <el-select :disabled="taskData.done" v-model="taskData.keyType" clearable placeholder="请选择算法模块">
                  <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>  
      <transition name="upload" mode="out-in">
        <!-- 按钮部分 -->
        <div class="btn-groups" v-if="!taskData.done">
          <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
          <button :disabled="taskData.createFlag" type="button" class="btn" @click="handleOne">请求</button>
        </div>
        <div class="data-show" v-else>
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>公钥密文</h3>
            <div class="data-title-actions">
              <span class="action aniTxtBtn" @click="copyText('keyOneText', taskData, '密文为空，请稍后重试或联系管理员')">复制</span>
              <span class="action aniTxtBtn" @click="downText('keyOneText', taskData, '未提供密文，请稍后重试或联系管理员')">下载</span>
            </div>
          </div>
          <div class="data-table data-table-scroll">
              <p class="text-container">
                {{ changeJSON(taskData.keyOneText) }}
              </p>
            </div>
          </div>
      </transition>
      </el-form>
      <!-- 第二步 -->
      <el-form ref="twoForm" :model="twoData" :rules="rules" v-if="taskData.done">
         <!-- 第一步配置 -->
        <div class="data-show">
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>上传协商密钥参数</h3> 
          </div>
          <!-- 内容区 -->
          <div class="data-table">
            <!-- 通用布局行 - 公钥密文 -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.keyTwoTextFilePath.showFileList}">
                <el-tooltip content="切换上传方式" placement="top">
                  <label class="condition-label condition-label-change" @click="changeUploadType('keyTwoTextFilePath', twoData)">协商密钥参数密文</label>
                </el-tooltip>
                <el-form-item class="condition-input" prop="keyTwoTextFilePath">
                  <el-upload
                    drag
                    class="upload"
                    :disabled="twoData.done"
                    v-if="uploadObj.keyTwoTextFilePath.isUploadType"
                    :ref="uploadObj.uploadRef('keyTwoTextFilePath')"
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.keyTwoTextFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('keyTwoTextFilePath')"
                    :on-success="uploadObj.onSuccess('keyTwoTextFilePath', twoData, twoForm)"
                    :on-progress="uploadObj.onProgress('keyTwoTextFilePath')"
                    :on-error="uploadObj.onError('keyTwoTextFilePath')"
                    :on-remove="uploadObj.onRemove('keyTwoTextFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!twoData.keyTwoTextFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.keyTwoTextFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                  <el-input v-else :disabled="twoData.done" type="textarea" @input="clearData('keyTwoTextFilePath', twoData)" @change="createBlobTxt($event, 'keyTwoTextFilePath', twoData, twoForm)" v-model="uploadObj.keyTwoTextFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <transition name="upload">
          <!-- 按钮部分 -->
          <div class="btn-groups" v-show="!twoData.done">
            <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
            <button :disabled="twoData.btnFlag" type="button" class="btn" @click="handleTwo">上传</button>
          </div>
        </transition>
      </el-form>
      <!-- 第三部 -->
      <el-form ref="threeForm" :model="threeData" :rules="rules" v-if="twoData.done">
        <div class="data-show">
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>文件上传</h3> 
          </div>
          <!-- 内容区 -->
          <div class="data-table">
            <!-- 通用布局行 -->
            <div class="common-row">
              <div class="common-item item-5">
                <label class="condition-label">参数选择</label>
                <el-form-item class="condition-input" prop="parameter">
                  <el-select :disabled="threeData.done" v-model="threeData.parameter" clearable placeholder="请选择参数文件">
                    <el-option v-for="(item, index) in parameters" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="common-item item-5">
                <label class="condition-label">任务类型</label>
                <el-form-item class="condition-input" prop="module">
                  <el-select :disabled="threeData.done" @change="moduleChange" v-model="threeData.module" clearable placeholder="请选择类型">
                    <el-option v-for="(item, index) in modules" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <!-- 通用布局行 - 签名文件上传 -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.signatureFilePath.showFileList}">
                <el-tooltip content="切换上传方式" placement="top">
                  <label class="condition-label condition-label-change" @click="changeUploadType('signatureFilePath', threeData)">签名文件</label>
                </el-tooltip>
                <el-form-item class="condition-input" prop="signatureFilePath">
                  <el-upload
                    v-if="uploadObj.signatureFilePath.isUploadType"
                    class="upload"
                    :disabled="threeData.done"
                    :ref="uploadObj.uploadRef('signatureFilePath')"
                    drag
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.signatureFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('signatureFilePath')"
                    :on-success="uploadObj.onSuccess('signatureFilePath', threeData, threeForm)"
                    :on-progress="uploadObj.onProgress('signatureFilePath')"
                    :on-error="uploadObj.onError('signatureFilePath')"
                    :on-remove="uploadObj.onRemove('signatureFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!threeData.signatureFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.signatureFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                  <el-input :disabled="threeData.done" v-else type="textarea" @input="clearData('signatureFilePath', threeData)" @change="createBlobTxt($event, 'signatureFilePath', threeData, threeForm)" v-model="uploadObj.signatureFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                </el-form-item>
              </div>
            </div>
            <!-- 通用布局行 - prompt上传 -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.promptFilePath.showFileList}">
                <el-tooltip content="切换上传方式" placement="top">
                  <label class="condition-label condition-label-change" @click="changeUploadType('promptFilePath', threeData)">提示词</label>
                </el-tooltip>
                <el-form-item class="condition-input" prop="promptFilePath">
                  <el-upload
                    v-if="uploadObj.promptFilePath.isUploadType"
                    class="upload"
                    :disabled="threeData.done"
                    :ref="uploadObj.uploadRef('promptFilePath')"
                    drag
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.promptFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('promptFilePath')"
                    :on-success="uploadObj.onSuccess('promptFilePath', threeData, threeForm)"
                    :on-progress="uploadObj.onProgress('promptFilePath')"
                    :on-error="uploadObj.onError('promptFilePath')"
                    :on-remove="uploadObj.onRemove('promptFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!threeData.promptFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.promptFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                  <el-input :disabled="threeData.done" v-else type="textarea" @input="clearData('promptFilePath', threeData)" @change="createBlobTxt($event, 'promptFilePath', threeData, threeForm)" v-model="uploadObj.promptFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                </el-form-item>
              </div>
            </div>
            <!-- 通用布局行 - 载体图片 -->
            <div class="common-row" key="stegoFilePath">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.stegoFilePath.showFileList}">
                <label class="condition-label">载密文件</label>
                <el-form-item class="condition-input" prop="stegoFilePath">
                  <el-upload
                    class="upload"
                    :disabled="threeData.done"
                    :ref="uploadObj.uploadRef('stegoFilePath')"
                    drag
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.stegoFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('stegoFilePath')"
                    :on-success="uploadObj.onSuccess('stegoFilePath', threeData, threeForm)"
                    :on-progress="uploadObj.onProgress('stegoFilePath')"
                    :on-error="uploadObj.onError('stegoFilePath')"
                    :on-remove="uploadObj.onRemove('stegoFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!threeData.stegoFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.stegoFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <transition name="upload">
          <!-- 底部的按钮 -->
          <div class="btn-groups" v-if="!threeData.done">
            <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
            <button type="button" :disabled="threeData.btnFlag" class="btn" @click="handleThree">上传</button>
          </div>
        </transition>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import useAppStore from '@/stores/app';
import { ref, computed, watch, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { API } from '@/utils/status.js';
import { ElMessage } from 'element-plus';
import * as uploadApi from '@/api/file';
import * as request from '@/api/steganography';
import * as rule from '@/utils/rules';


const router = useRouter();
const route = useRoute();
const systems = API.steganography.systems;
const parameters = API.steCommon.parameters;
const modules = API.steCommon.modules;
const keyTypes = API.publicSteg.keyTypes;
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];
const configs = [
  { value: 'config1', label: 'ECC参数文件' },
  { value: 'config2', label: 'RSA参数文件' }
];
const defaultTaskData = {
  done: false,
  createFlag: false,
  name: '',
  system: null,
  type: null,
  description: '',
  userID: null,
  keyType: null,
  // ==
  keyOneText: null
};
const defaultTwoData = {
  btnFlag: false,
  done: false,
  keyTwoTextFilePath: null
};
const defaultThreeData = {
  done: false,
  btnFlag: false,
  signatureFilePath: null,
  stegoFilePath: null,
  promptFilePath: null,
  module: null,
  parameter: null
}
const defaultUpload = {
  isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
}


// ============> data <============
const appStore = useAppStore();
const taskForm = ref(null);
const twoForm = ref(null);
const threeForm = ref(null);
const taskData = ref({
  done: false,
  createFlag: false,
  name: '',
  system: null,
  type: null,
  description: '',
  userID: null,
  keyType: null,
  // ==
  keyOneText: null
});
const twoData = ref({
  btnFlag: false,
  done: false,
  keyTwoTextFilePath: null
});
const threeData = ref({
  done: false,
  btnFlag: false,
  signatureFilePath: null,
  stegoFilePath: null,
  promptFilePath: null,
  module: null,
  parameter: null
});

const uploadObj = ref({
  uploadUrl: `${import.meta.env.VITE_FILE_BASE_API}${uploadApi.uploadUrl}`,
  uploadRef(key){
    return function (dom){
      if (dom){
        uploadObj.value[key].dom = dom;
      }
    }
  },
  beforeUpload(key){
    return function (file){
      if (uploadObj.value[key].uploading){
        ElMessage.warning('当前有文件正在上传，请稍后重试');
        return false;
      }
      let extension = file.size < API.upload.commonLimit;
      if (!extension) {
        ElMessage.warning(`上传文件超过大小限制，文件须小于${API.upload.commonLimit / (1024 * 1024)}M`)
      }
      if (key === 'keyTwoTextFilePath' || key === 'signatureFilePath'){
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
        extension = fileType == 'json' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为json文件!');
        }
      }
      if (key === 'promptFilePath' || (key === 'stegoFilePath' && threeData.value.module === '文本')){
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
        extension = fileType == 'txt' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为txt文件!');
        }
      }
      // if (key === 'stegoFilePath' && threeData.value.module === '图像') {
      //   let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      //   extension = (fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg') ? true : false;
      //   if (!extension){
      //     ElMessage.warning('上传文件须为jpg/png/jpeg文件!');
      //   }
      // }
      // if (key === 'stegoFilePath' && threeData.value.module === '音频'){
      //   let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      //   extension = (fileType == 'wav' || fileType == 'mp3') ? true : false;
      //   if (!extension){
      //     ElMessage.warning('上传文件须为wav/mp3文件!');
      //   }
      // }
      uploadObj.value[key].fileName = extension ? file.name : '';
      uploadObj.value[key].showFileList = true;
      return extension;
    }
  },
  onSuccess(key, targetObj, form){
    return function (e){
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      if (e.code === API.code.SUCCESS) { 
        ElMessage.success('上传成功');
        targetObj[key] = e.data.path;
      } else {
        let msg = e.msg || e.message || '上传失败，请稍后重试或联系管理员';
        ElMessage({
          type: 'error',
          duration: 1500,
          message: msg
        });
      }
      form.validateField([key])
    }
  },
  onProgress(key){
    return function (e){
      uploadObj.value[key].showFileList = true;
      uploadObj.value[key].uploading = true;
    }
  },
  onError(key){
    return function (e){
      console.log(e)
      let message = e.msg || e.message || '上传失败，请稍后重试或联系管理员'
      ElMessage({
        type: 'error',
        duration: 1500,
        message
      });
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  onRemove(key){
    return function (e){
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  keyTwoTextFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  signatureFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  stegoFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  promptFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  }
});
const rules = {
  name: rule.createRequired('任务名称不能为空'),
  userID: rule.createRequired('用户名不能为空'),
  keyType: rule.createRequired('算法模块不能为空'),
  module: rule.createRequired('请选择任务类型'),
  // keyTwoTextFilePath: rule.createRequired('请上传协商密钥参数密文'),
  keyTwoTextFilePath: rule.createTextUpload(uploadObj.value, 'keyTwoTextFilePath', '协商密钥参数密文不能为空'),
  // signatureFilePath: rule.createRequired('请上传签名文件'),
  signatureFilePath: rule.createTextUpload(uploadObj.value, 'signatureFilePath', '签名文件不能为空'),
  // promptFilePath: rule.createRequired('请上传关键词'),
  promptFilePath: rule.createTextUpload(uploadObj.value, 'promptFilePath', '提示词不能为空'),
  stegoFilePath: rule.createRequired('请上传载密文件')
};
const changeJSON = computed(() => {
  return function (jsonString){
    return jsonString ? window.decodeURIComponent(JSON.parse(jsonString)) : '';
  }
})

// ============> hooks <============
onActivated(() => {
  let { id, isCreate, reenter } = route.query;
  if (reenter || (id !== undefined && id == taskData.value.id)){
    return;
  }
  if (isCreate){
    init();
    return;
  }
  reInit();
});

// ============> methods <============
function init(){
  taskData.value = Object.assign({}, defaultTaskData);
  twoData.value = Object.assign({}, defaultTwoData);
  threeData.value = Object.assign({}, defaultThreeData);
  uploadObj.value.keyTwoTextFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.signatureFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.promptFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.stegoFilePath = Object.assign({}, defaultUpload);
}
function reInit(){
  let {id} = route.query;
  init();
  request.getTaskDetailById({id})
    .then(res => {
      let result = res;
      result.infoData = JSON.parse(res.infoData);
      console.log(result);
      taskData.value.id = result.id;
      taskData.value.name = result.name;
      taskData.value.description = result.description;
      taskData.value.keyType = result.infoData.keyType;
      taskData.value.userID = result.infoData.userID;
      if (result.status >= 1){
        taskData.value.done = true;
        taskData.value.createFlag = false;
        taskData.value.keyOneText = result.infoData.keyOneText;
      }
      if (result.status >= 2 && res.infoData && res.infoData.keyTwoTextFilePath){
        twoData.value.done = true;
        twoData.value.btnFlag = false;
        twoData.value.keyTwoTextFilePath = result.infoData.keyTwoTextFilePath;
        uploadObj.value.keyTwoTextFilePath.fileName = 'keyTwoText.json';
      }
      if (result.status >= 3){
        threeData.value.done = true;
        threeData.value.btnFlag = false;
        threeData.value.promptFilePath = result.infoData.promptFilePath;
        threeData.value.stegoFilePath = result.infoData.stegoFilePath;
        threeData.value.signatureFilePath = result.infoData.signatureFilePath;
        threeData.value.module = result.infoData.module;
        threeData.value.parameter = result.infoData.parameter;
        uploadObj.value.signatureFilePath.fileName = 'signature.json';
        uploadObj.value.promptFilePath.fileName = 'prompt.txt';
        let messageName = 'stego';
        switch (result.infoData.module){
          case '图像':
            messageName += '.png';
            break;
          case '文本':
            messageName += '.txt';
            break;
          case '音频':
            messageName += '.wav';
            break;
        }
        uploadObj.value.stegoFilePath.fileName = messageName;
      }
    })
}
// 通用复制
function copyText(key, data, warning = '内容为空，请稍后重试或联系管理员'){
  if (!data[key]) {
    ElMessage.warning(warning);
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(data[key])
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = data[key];
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 通用下载
function downText(key, data, warning = '下载内容为空，请稍后再试或联系管理员', filename='keyText.json'){
  if (!data[key]){
    ElMessage.warning(warning);
    return;
  }
  const blob = new Blob([data[key]], { type: 'application/json' });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = filename;
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
function changeUploadType(key, data){
  if (data && data.done){
    return;
  }
  uploadObj.value[key].isUploadType = !uploadObj.value[key].isUploadType;
  uploadObj.value[key].text = '';
  uploadObj.value[key].showFileList = false;
  uploadObj.value[key].fileName = '';
  uploadObj.value[key].uploading = false;
  data[key] = null;
}
function clearData(key, data){
  data[key] = '';
}
function createBlobTxt(e, key, data, form){
  if (!e){
    data[key] = null;
    ElMessage.success('上传成功');
    return;
  }
  let fileType, filename;
  switch (key){
    case 'keyTwoTextFilePath':
      filename = 'keyTwoText.json';
      fileType = 'application/json';
      break;
    case 'signatureFilePath':
      filename = 'signature.json';
      fileType = 'application/json';
      break;
    case 'promptFilePath':
      filename = 'prompt.txt';
      fileType = 'text/plain';
      break;
  }
  const blob = new Blob([e], { type: fileType});
  const file = new File([blob], filename, { type: fileType});
  let formData = new FormData();
  formData.append('file', file);
  uploadApi.upload(formData)
    .then(res => {
      console.log(res);
      ElMessage.success('上传成功');
      data[key] = res.path;
      uploadObj.value[key].fileName = filename;
      form.validateField([key]);
    })
    .catch(err => {
      console.log(err);
      let msg = err.msg || err.message || '上传失败，请稍后重试或联系管理员';
      ElMessage.error(msg);
      form.validateField([key]);
    })
}
function moduleChange(){
  threeData.value.stegoFilePath = null;
  uploadObj.value.stegoFilePath.fileName = '';
}
function handleCancel(){
  router.back();
}
function handleOne(){
  if (taskData.value.createFlag){
    ElMessage.warning('当前正在执行，请稍后');
    return;
  }
  taskForm.value.validate(valid => {
    if (valid){
      taskData.value.createFlag = true;
      appStore.openLoading('公钥请求中...');
      request.appThreeWebRequstKey({
        name: taskData.value.name,
        moduleType: API.steganography.moduleType.APPTHREE,
        taskType: API.steganography.type.IMPLANT,
        infoData: {
          userID: taskData.value.userID,
          keyType: taskData.value.keyType
        }
      })
        .then(res => {
          console.log(res);
          taskData.value.createFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.keyOneText){
            ElMessage.success('请求公钥成功');
            taskData.value.done = true;
            taskData.value.id = res.id;
            taskData.value.keyOneText = res.infoData.keyOneText;
          } else {
            ElMessage.error('请求公钥失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          taskData.value.createFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对');
    }
  })
}
function handleTwo(){
  if (twoData.value.btnFlag){
    ElMessage.warning('当前正在执行，请稍后');
    return;
  }
  twoForm.value.validate(valid => {
    if (valid){
      twoData.value.btnFlag = true;
      appStore.openLoading('参数上传中...');
      request.appThreeWebUploadKey({
        id: taskData.value.id,
        infoData: {
          keyTwoTextFilePath: twoData.value.keyTwoTextFilePath
        }
      })
        .then(res => {
          console.log(res);
          twoData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.status == 2){
            ElMessage.success('参数上传成功');
            twoData.value.done = true;
          } else {
            ElMessage.error('参数上传失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          twoData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对');
    }
  })
}
function handleThree(){
  if (threeData.value.btnFlag){
    ElMessage.warning('当前正在执行，请稍后');
    return;
  }
  threeForm.value.validate(valid => {
    if (valid){
      threeData.value.btnFlag = true;
      appStore.openLoading('上传中...');
      request.appThreeWebSign({
        id: taskData.value.id,
        infoData: {
          userID: taskData.value.userID,
          keyType: taskData.value.keyType,
          signatureFilePath: threeData.value.signatureFilePath,
          module: threeData.value.module,
          parameter: threeData.value.parameter,
          promptFilePath: threeData.value.promptFilePath,
          stegoFilePath: threeData.value.stegoFilePath
        }
      })
        .then(res => {
          console.log(res);
          threeData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.status == 3){
            ElMessage.success('上传成功');
            threeData.value.done = true;
          } else {
            ElMessage.warning('上传失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          threeData.value.btnFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对');
    }
  })
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-5 {
  width: 49%;
  // height: auto;
  // padding: 50px 0 60px 0;
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 20px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.item-upload {
  padding-bottom: 50px;
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
.audio-container {
  width: 100%;
  height: 190px;
  background-color: var(--color-gray-2);
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  @include flex-all-center;
  .audio-icon {
    font-size: 40px;
    font-weight: bolder;
    color: var(--color-main);
  }
  .audio {
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 105%;
    height: 30px;
    transform: translateX(-50%);
  }
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
  .file-image {
    width: 100%;
    height: 190px;
    background-color: var(--color-gray-2);
    border: 1px solid var(--color-main-border);
    border-radius: 6px;
  }
}
</style>